import logging

from flask import Blueprint, request, jsonify

from mysql_tool.mysql_tool import MySQLTool

# 创建蓝图
fixtures_receive_api = Blueprint('fixtures_receive_api', __name__)

# 设置日志
logger = logging.getLogger(__name__)


@fixtures_receive_api.route('/api/fixtures/receive', methods=['POST'])
def receive_fixture():
    """治具领用API接口"""
    try:
        # 获取请求参数
        data = request.get_json()

        # 验证必要参数
        fixture_id = data.get('fixSn')
        wo_code = data.get('wocode')

        if not fixture_id or not wo_code:
            return jsonify({
                "success": False,
                "message": "缺少必要参数: fixtureId 或 woCode"
            }), 400

        # 获取可选参数
        recipient = data.get('recipient', '郑文博1')  # 领用人
        step = data.get('step', '上线')  # 步骤
        mate_id = data.get('mateId', '')  # 材料ID

        # 创建数据库连接
        mysql_tool = MySQLTool('172.27.32.57', 'root', 'zc123456', 'a50', '9988')

        # 先查询sfcdatmes_fix_vstorage表获取正确的ReelID和MateID
        verify_sql = """
                     SELECT ReelID, MateID
                     FROM sfcdatmes_fix_vstorage
                     WHERE ReelID = %s
                     """

        # 执行查询
        result = mysql_tool.execute_query(verify_sql, (fixture_id,))

        # 检查是否找到匹配记录
        if not result or len(result) == 0:
            logger.error(f"未找到匹配的材料ID: {fixture_id}")
            return jsonify({
                "success": False,
                "message": f"未找到匹配的材料ID: {fixture_id}"
            }), 404

        # 使用查询结果中的值
        reel_id = result[0][0]  # 从查询结果获取ReelID
        verified_mate_id = result[0][1]  # 从查询结果获取MateID

        # 构建SQL插入语句
        sql = """
              INSERT INTO sfcdatmes_fix_log (ReelID, Step, MateID, Recipient, wocode)
              VALUES (%s, %s, %s, %s, %s)
              """

        # 准备参数，使用从数据库查询到的值
        params = (reel_id, step, verified_mate_id, recipient, wo_code)

        # 执行SQL插入
        rows_affected = mysql_tool.execute_insert(sql, params)

        # 更新治具库存当中的状态 - 将状态更新为3并绑定当前工单
        update_status_sql = """
                            UPDATE sfcdatmes_fix_vstorage
                            SET Status = 3,
                                Wocode = %s
                            WHERE ReelID = %s
                            """
        update_params = (wo_code, reel_id)
        update_result = mysql_tool.execute_query(update_status_sql, update_params)

        if rows_affected > 0:
            logger.info(f"治具上线成功: 治具SN={fixture_id}, 工单={wo_code}, 领用人={recipient}")
            return jsonify({
                "success": True,
                "message": "治具领用记录创建成功",
                "data": {
                    "fixtureId": fixture_id,
                    "woCode": wo_code,
                    "recipient": recipient,
                }
            })
        else:
            logger.error(f"治具领用失败: 治具SN={fixture_id}, 工单={wo_code}")
            return jsonify({
                "success": False,
                "message": "治具领用记录创建失败"
            }), 500

    except Exception as e:
        logger.error(f"治具领用API异常: {str(e)}")
        return jsonify({
            "success": False,
            "message": f"处理请求时发生错误: {str(e)}"
        }), 500


@fixtures_receive_api.route('/api/fixtures/online', methods=['POST'])
def fixture_online():
    """治具上线API接口 """
    try:
        # 获取请求参数
        data = request.get_json()

        # 验证必要参数
        line = data.get('line')
        fix_sn = data.get('fixSn')
        product_id = data.get('productId')
        wo_code = data.get('wocode')
        fix_surface = data.get('fixSurface')

        if not line or not fix_sn or not product_id or not wo_code or not fix_surface:
            return jsonify({
                "success": False,
                "message": "缺少必要参数: line, fixSn, productId 或 woCode fixSurface"
            }), 200

        # 创建数据库连接
        mysql_tool = MySQLTool()

        # 根据fix_sn查询治具信息
        verify_sql = """
                     SELECT id,
                            product_id,
                            product_name,
                            fix_type,
                            fix_sn,
                            fix_status,
                            fix_surface
                     FROM smt_fix_config
                     WHERE fix_sn = %s
                     """

        # 执行查询
        results = mysql_tool.execute_query(verify_sql, (fix_sn,))

        # 检查是否找到匹配记录
        if not results or len(results) == 0:
            logger.error(f"未找到匹配的治具ID: {fix_sn}")
            return jsonify({
                "success": False,
                "message": f"未找到匹配的治具ID: {fix_sn}"
            }), 200

        # 查找与请求中product_id匹配的记录
        matched_record = None
        for result in results:
            if result[1] == product_id:  # 比较product_id
                matched_record = result
                break

        # 如果没有找到匹配的产品记录
        if not matched_record:
            logger.error(f"治具{fix_sn}不支持产品{product_id}")
            return jsonify({
                "success": False,
                "message": f"治具{fix_sn}不支持产品{product_id}，请使用正确的治具"
            }), 200

        # 使用匹配记录中的值
        fix_id = matched_record[0]  # 治具ID
        fix_product_id = matched_record[1]  # 产品ID
        fix_type = matched_record[3]  # 治具类型
        fix_status = matched_record[5]  # 治具状态
        db_fix_surface = matched_record[6]  # 治具表面(T/B面)

        # 检查治具状态
        if fix_status != "在库":
            logger.error(f"治具状态不可用: {fix_sn}, 当前状态: {fix_status}")
            return jsonify({
                "success": False,
                "message": f"治具状态不可用，当前状态: {fix_status}"
            }), 200

        # 查找当前产线上正在使用的同类型治具
        current_fixture_sql = """
                              SELECT id, fix_sn, fix_type
                              FROM smt_fix_config
                              WHERE line = %s
                                AND fix_type = %s
                                AND fix_status = '使用中'
                              """
        current_fixtures = mysql_tool.execute_query(current_fixture_sql, (line, fix_type))

        # 如果找到了正在使用的治具，将其状态更新为"在库"
        if current_fixtures and len(current_fixtures) > 0:
            for current_fixture in current_fixtures:
                current_fix_id = current_fixture[0]
                current_fix_sn = current_fixture[1]

                # 更新当前在用治具状态为"在库"
                update_current_sql = """
                                     UPDATE smt_fix_config
                                     SET fix_status = '在库',
                                         line       = NULL,
                                         wocode     = NULL
                                     WHERE id = %s
                                     """
                mysql_tool.execute_insert(update_current_sql, (current_fix_id,))
                logger.info(f"治具{current_fix_sn}已自动下线")

        # 更新新治具状态为"使用中"
        update_new_sql = """
                         UPDATE smt_fix_config
                         SET fix_status = '使用中',
                             line       = %s,
                             wocode     = %s
                         WHERE id = %s
                         """

        mysql_tool.execute_insert(update_new_sql, (line, wo_code, fix_id))
        logger.info(f"治具{fix_sn}已上线到产线{line}")

        # 所有验证通过，返回成功
        logger.info(f"治具验证通过: 治具SN={fix_sn}, 线别={line}, 产品={product_id}, 工单={wo_code}")
        return jsonify({
            "success": True,
            "message": "治具验证通过并已上线",
            "data": {
                "fixSn": fix_sn,
                "line": line,
                "productId": product_id,
                "woCode": wo_code,
                "fixType": fix_type,
                "fixSurface": fix_surface
            }
        })

    except Exception as e:
        logger.error(f"治具上线API异常: {str(e)}")
        return jsonify({
            "success": False,
            "message": f"处理请求时发生错误: {str(e)}"
        }), 500
